package com.share51.novel.service.impl;

import com.google.common.collect.ImmutableList;
import com.share51.novel.common.StatusConstant;
import com.share51.novel.common.ViewConstant;
import com.share51.novel.config.NovelConfig;
import com.share51.novel.entity.Novel;
import com.share51.novel.init.ApplicationCached;
import com.share51.novel.init.CategoryVo;
import com.share51.novel.service.NovelService;
import com.share51.novel.service.PageService;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 页面请求数据处理
 *
 * @author gb
 */
@Service("pageService")
public class PageServiceImpl implements PageService {

    @Resource
    private NovelConfig novelConfig;

    @Resource
    private NovelService novelService;

    private static final String REFERER_PREFIX="%s://%s/detail/%d.html";

    @Override
    public ResponseEntity<FileSystemResource> download(Integer novelId, HttpServletRequest request) throws UnsupportedEncodingException {
        String referer = request.getHeader("Referer");
        String targetReferer = String.format(REFERER_PREFIX,
                novelConfig.isEnableSsl()?"https":"http",
                novelConfig.getHostName(), novelId);
        if (!targetReferer.equalsIgnoreCase(referer)){
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        Novel novel=novelService.getNovelInfoByDownload(novelId);
        if (novel==null||novel.getStatus()!=StatusConstant.STATUS_OK){
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        File file = new File(novelConfig.getSaveFilePath()+ViewConstant.NOVEL_SAVE_URL+novel.getId()+".zip");
        if (file.exists()){
            FileSystemResource resource = new FileSystemResource(file);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            String fileName=novelConfig.getHostName()+"@"+novel.getName()+"_"+novel.getAuthor()+".zip";
            headers.add("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName,"utf-8"));
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            headers.add("Content-Length", file.length() + "");
            headers.add("Content-Type", "application/octet-stream");
            return new ResponseEntity<>(resource, headers, HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    @Override
    public void toIndex(Model model) {
        ImmutableList<CategoryVo> menuList = ApplicationCached.getMenuList();
        model.addAttribute("menuList",menuList);
        // 获取最新更新的 20 本小说
        List<Novel> list=novelService.getNewest(20,null);
        model.addAttribute("newest",list);
    }
}
